<?php
/**
 * PHP Framework Integration HTTP Web Service Reference class
 * This class implements generic HTTP web service reference
 *
 * @author Andrew <andrew@vitche.com>
 * @author Frozen Rain <frozenrain@mail.ru>
 **/
class HTTPWebServiceReference extends WebServiceReference {

    /**
     * Makes a call to the HTTP web service
     * @param String $method A method to be called
     * @param Array $arguments Arguments to be passed during the call
     **/
    public function execute($method, $arguments) {

        // Build the call URL
        $url = "$this->_uri?$method";
        foreach ($arguments as $key => $value) {
            $url .= "&$key=$value";
        }

        return $this->post($url);
    }

    /**
     * Makes a POST HTTP request from a GET HTTP request
     * with an optional ability to specify HTTP headers
     * @param String $url Url to make request to
     * @param Array $headers Optional headers for an HTTP request
     * @return String Resulting response
     **/
    private function post($url, $headers = false) {

        $url = parse_url($url);

        if (!isset($url['port'])) {
            if ($url['scheme'] == 'http') {
                $url['port'] = 80;
            } else if ($url['scheme'] == 'https') {
                $url['port'] = 443;
            }
        }

        $url['query'] = isset($url['query']) ? $url['query'] : '';
        $url['protocol'] = $url['scheme'] . '://';
        $eol = "\r\n";
        $headers = "POST " . $url['protocol'] . $url['host'] . $url['path'] .
            " HTTP/1.0" . $eol.
            "Host: " . $url['host'] . $eol .
            "Referer: " . $url['protocol'] . $url['host'] . $url['path'] . $eol.
            "Content-Type: application/x-www-form-urlencoded" . $eol .
            "Content-Length: " . strlen($url['query']) . $eol .
            $eol . $url['query'];
        $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
        if($fp) {
            fputs($fp, $headers);
            $result = '';
            while(!feof($fp)) {
                $result .= fgets($fp, 128);
            }

            fclose($fp);
            if (!$headers) {
                $pattern = "/^.*\r\n\r\n/s";
                $result = preg_replace($pattern, '', $result);
            }

            return $result;
        }
    }
}
?>